const {parseToken}=require('../utils/tokenHandler')
const {TOKEN_IS_REQURIED,TOKEN_IS_ERROR}=require('../error/errorType')

const auth=async(ctx,next)=>{
    const {authorization}=ctx.request.header
    if(!authorization){
        return ctx.app.emit('error',new Error(TOKEN_IS_REQURIED),ctx)
    }
    let token=authorization.replace('Besc ',"")
    let user
    try{
        user=parseToken(token)
    }catch{
        return ctx.app.emit('error',new Error(TOKEN_IS_ERROR),ctx)
    }
    ctx.tokenInfo=user

    await next()
}

module.exports={
    auth
}